<template>
	<div style="width: 50%;">
		<el-form :model="form" :rules="rules" ref="formm">
			<el-form-item label="专题标题" :label-width="formLabelWidth" prop="title">
				<el-input v-model="form.title" autocomplete="off"></el-input>
			</el-form-item>
			<el-form-item label="专题子标题" :label-width="formLabelWidth" prop="subtitle">
				<el-input v-model="form.subtitle" autocomplete="off"></el-input>
			</el-form-item>

			<el-form-item label="专题图片" :label-width="formLabelWidth" prop="picUrl">
				<el-upload class="avatar-uploader" action="http://192.168.1.54:8080/admin/storage/create"
					:headers="token" :show-file-list="false" :on-success="handleAvatarSuccess"
					:before-upload="beforeAvatarUpload">
					<img v-if="form.picUrl" :src="form.picUrl" class="avatar">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
			</el-form-item>

			<el-form-item label="专题内容" :label-width="formLabelWidth" prop="content">
				<Links :init="editorInit" v-model="form.content"></Links>
			</el-form-item>

			<el-form-item label="专题低价" :label-width="formLabelWidth" prop="price">
				<el-input v-model="form.price" autocomplete="off"></el-input>
			</el-form-item>

			<el-form-item label="阅读量" :label-width="formLabelWidth">
				<el-input v-model="form.readCount" autocomplete="off"></el-input>
			</el-form-item>


			<el-row style="text-align: right;">
				<el-button size="mini" type="primary" @click="kon();dialogVisible = true">创建商品</el-button>
			</el-row>


			<el-form-item label="专题商品" :label-width="formLabelWidth">
				<el-table :data="goods" border style="width: 100%">
					<el-table-column align="center" prop="id" label="商品ID">
					</el-table-column>
					<el-table-column align="center" prop="picUrl" label="图片">
						<template slot-scope="scope">
							<img width="80px" height="80px" :src="scope.row.picUrl" v-if="scope.row.picUrl" />
						</template>
					</el-table-column>
					<el-table-column align="center" prop="name" label="商品名称">
					</el-table-column>
					<el-table-column align="center" prop="brief" label="商品介绍">
					</el-table-column>
					<el-table-column align="center" prop="operation" label="操作">
						<template slot-scope="scope">
							<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button>取 消</el-button>
			<el-button type="primary" @click="add()">确 定</el-button>
		</div>




		<el-dialog title="提示" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
			<div>
				<el-input size="mini" v-model="input" placeholder="请输入商品编号" clearable style="width: 30%;"
					@clear="Baidu()">
				</el-input>
				<el-input size="mini" v-model="input1" placeholder="请输入商品名称" clearable @clear="Baidu()"
					style="width: 30%;margin: 0px 3px;">
				</el-input>
				<el-button size="mini" type="primary" icon="el-icon-search" @click="Baidu()">查找</el-button>
			</div>

			<el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" border
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55">
				</el-table-column>
				<el-table-column align="center" prop="id" label="商品ID">
				</el-table-column>
				<el-table-column align="center" prop="picUrl" label="图片">
					<template slot-scope="scope">
						<img width="80px" height="80px" :src="scope.row.picUrl" v-if="scope.row.picUrl" />
					</template>
				</el-table-column>
				<el-table-column align="center" prop="name" label="商品名称">
				</el-table-column>
			</el-table>

			<!-- //分页 -->
			<div v-if="tableData.length>0">
				<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page="ljq.page" :page-sizes="[5, 10, 15, 20]" :page-size="ljq.num"
					layout="total, sizes, prev, pager, next, jumper" :total="ljq.total">
				</el-pagination>
			</div>


			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="adde();dialogVisible = false">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import Cookie from 'js-cookie'
	import Links from '@tinymce/tinymce-vue'
	import {
		topicCreate,
		goodsList
	} from '../../../utils/axios.js'

	export default {
		components: {
			Links
		},
		data() {
			return {


				//分页
				ljq: {
					page: 1, //默认前往几页
					num: 20, //默认一页几条
					total: 0, //共几条
				},

				all:[],
				input: '',
				input1: '',

				tableData: [],
				multipleSelection: [],

				dialogVisible: false,


				token: {
					'X-Litemall-Admin-Token': Cookie.get('token')
				},

				goods: [],
				goodsIds: [],



				form: {
					title: '', //专题标题
					subtitle: '', //专题子标题
					content: '', //专题内容
					picUrl: '', //专题专题图片
					price: '', //商品低价
					readCount: '', //阅读量
				},
				formLabelWidth: '120px',

				//不能为空
				rules: {
					title: [{
						required: true, //必填
						message: "专题标题不能为空",
						trigger: 'blur' //离开
					}],
					subtitle: [{
						required: true, //必填
						message: "专题子标题不能为空",
						trigger: 'blur' //离开
					}],
					content: [{
						required: true, //必填
						message: "专题内容不能为空",
						trigger: 'blur' //离开
					}],
					price: [{
						required: true, //必填
						message: "专题低价不能为空",
						trigger: 'blur' //离开
					}],
				},

				//富文本编辑器
				editorInit: {
					language: 'zh_CN',
					height: 500,
					skin_url: "/skins/ui/oxide",
					convert_urls: false,
					plugins: [
						'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
					],
					toolbar: [
						'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
						'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
					],
					images_upload_handler: function(blobInfo, success, failure) {
						const formData = new FormData();
						formData.append('file', blobInfo.blob());
						createStorage(formData)
							.then(res => {
								success(res.data.data.url);
							})
							.catch(() => {
								failure('上传失败，请重新上传');
							});
					}
				},
			}
		},
		methods: {


			//查找
			Baidu() {
				goodsList(this.ljq.page, this.ljq.limit, this.input, this.input1, ).then(res => {
					// console.log(res);
					this.tableData = res.data.data.list
					this.ljq.total = res.data.data.total
				})
			},


			//分页
			handleSizeChange(new_num) {
				// console.log(newnum)
				this.ljq.num = new_num
				this.Baidu()
			},
			handleCurrentChange(new_page) {
				this.ljq.page = new_page
				this.Baidu()
			},



			//删除
			handleDelete(index, row) {
				// console.log(index, row);
				this.goods.splice(index, 1)
				this.goodsIds = []
				this.goods.forEach(item => {
					// console.log(item.id)
					this.goodsIds.push(item.id)
				})
				
			},
			kon(){
				this.tableData = []
			},
			adde(){
				this.goods = this.all
			},
			handleSelectionChange(val) {
				this.all=val
				// let all = [];
				// for (var i = 0; i < val.length; i++) {
				// 	all.push(val[i].id)
				// }
				// this.goods = all
			},

			//商品列表确认关闭
			handleClose(done) {
				this.$confirm('确认关闭？')
					.then(_ => {
						done();
					})
					.catch(_ => {});
			},


			//刷新
			refresh() {
				this.$router.push({
					path: '/SkipBlank',
					query: {
						path: this.$route.path
					}
				})
			},


			add() {
				console.log(this.goods);
				this.goods.forEach(item => {
					this.goodsIds.push(item.id)
				})
				let data = {
					title: this.form.title,
					subtitle: this.form.subtitle,
					content: this.form.content,
					picUrl: this.form.picUrl,
					price: this.form.price,
					readCount: this.form.readCount,
					goods: this.goodsIds
				}
				this.$refs.formm.validate((valid) => {
					if (valid) {
						topicCreate(data).then(res => {
							console.log(res);
							this.$router.push('/promotion/topic')
							this.$notify({
								title: '成功',
								message: '添加成功',
								type: 'success',
							});
						})
					} else {
						console.log('失败');
						return false;
					}
				});
			},







			handleAvatarSuccess(res, file) {
				this.form.picUrl = URL.createObjectURL(file.raw);
				this.form.picUrl = res.data.url
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			}
		}
	}
</script>

<style lang="less">
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 138px;
		height: 138px;
		line-height: 138px !important;
		text-align: center;
	}

	.avatar {
		width: 108px;
		height: 108px;
		display: block;
	}

	.el-form {
		font-weight: 800;
	}
</style>
